package com.changgou.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.service.FileService;
import com.changgou.utils.FastDFSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;

/**
 * @Author gentleman Ma
 * @Date created in 2020/2/15
 * @description  分布式文件控制器
 * @Version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;


    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file){
       String uploadResult = fileService.uploadFile(file);
       if (uploadResult == null){
           return new Result(false,StatusCode.ERROR,"文件不能为空");
       }

       return new Result(true, StatusCode.OK,"文件上传成功",uploadResult);
    }


    /**
     * 文件下载
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(){
        //http://192.168.200.128:8080/group1/M00/00/00/wKjIgF5IDYuADTq9AANyjXMg0c058..jpg
        String groupName ="group1";
        String remoteFileName = "M00/00/00/wKjIgF5IDYuADTq9AANyjXMg0c058..jpg";
        byte[] body = FastDFSClient.downFileBytes(groupName, remoteFileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            headers.setContentDispositionFormData("attachment",new String("黑马.jpg".getBytes("UTF-8"),"iso8859-1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(body,headers, HttpStatus.CREATED);
    }
}
